const dayjs = require('dayjs');
const groupBy = require('lodash.groupby');
// 获取最小数
const getMin = (a, b) => {
  return parseFloat(a) >= parseFloat(b) ? parseFloat(b) : parseFloat(a);
};

// 根据用户类型、认申购，计算起购金额
// 理财产品，1、8为申购；2为认购；默认个人户申购
// 除理财产品外，1为申购；2为认购；默认显示个人申购
const getPurchaseInfo = (userType, productInfo) => {
  // 个人户，默认申购
  let purchaseType = '申购';
  let purchaseFirst = productInfo.minPerfappBalance;
  let purchase = productInfo.minShare2;
  let purchasePace = productInfo.allotLimitshare2;
  if (productInfo.prodStatus === '2') {
    purchaseType = '认购';
    purchaseFirst = productInfo.openShare; // 暂不确定
    purchase = productInfo.minShare;
    purchasePace = productInfo.allotLimitshare;
  }

  if (userType === '1') {
    // 机构户，默认申购
    purchaseType = '申购';
    purchaseFirst = productInfo.minOrgfappBalance;
    purchase = productInfo.orgLowlimitBalance2;
    purchasePace = productInfo.orgAppendBalance2;
    if (productInfo.prodStatus === '2') {
      purchaseType = '认购';
      purchaseFirst = productInfo.minsize; // 暂不确定
      purchase = productInfo.orgLowlimitBalance;
      purchasePace = productInfo.orgAppendBalance;
    }
  }
  return {
    purchaseType,
    purchaseFirst,
    purchase,
    purchasePace,
    minPurchase: getMin(purchaseFirst, purchase)
  };
};

/* 将用户的风险能力等级转为对应的中文 */
const parseUserRisk = (userRisk) => {
  const userRiskArr = [
    { level: '1', userRiskText: '保守型' },
    { level: '2', userRiskText: '谨慎型' },
    { level: '3', userRiskText: '稳健型' },
    { level: '4', userRiskText: '积极型' },
    { level: '5', userRiskText: '激进型' },
    { level: '6', userRiskText: '原保守型' },
    { level: '7', userRiskText: '原稳健型' },
    { level: '8', userRiskText: '原成长型' },
    { level: '9', userRiskText: '原积极型' },
    { level: '10', userRiskText: '原激进型' },
    { level: '0', userRiskText: '默认型' }
  ];

  for (let i = 0, len = userRiskArr.length; i < len; i += 1) {
    if (userRiskArr[i].level === userRisk) {
      return userRiskArr[i].userRiskText;
    }
  }
  return '';
};

/* 将产品的风险等级转为对应的中文 */
const parseProdRisk = (prodRisk) => {
  const prodRiskArr = [
    { level: '1', prodRiskText: '低风险' },
    { level: '2', prodRiskText: '中低风险' },
    { level: '3', prodRiskText: '中风险' },
    { level: '4', prodRiskText: '中高风险' },
    { level: '5', prodRiskText: '高风险' },
    { level: '6', prodRiskText: '极高风险' },
    { level: '0', prodRiskText: '默认型' }
  ];

  for (let i = 0, len = prodRiskArr.length; i < len; i += 1) {
    if (prodRiskArr[i].level === prodRisk) {
      return prodRiskArr[i].prodRiskText;
    }
  }
  return '';
};

/* 计算产品的风险等级适用的用户风险等级 */
const parseSuitUserRisk = (prodRisk) => {
  const userRiskArr = [
    { level: '1', userRiskText: '保守型' },
    { level: '2', userRiskText: '谨慎型' },
    { level: '3', userRiskText: '稳健型' },
    { level: '4', userRiskText: '积极型' },
    { level: '5', userRiskText: '激进型' }
  ];
  const suitableArr = [];
  for (let i = 0, len = userRiskArr.length; i < len; i += 1) {
    if (userRiskArr[i].level >= prodRisk) {
      suitableArr.push(userRiskArr[i].userRiskText);
    }
  }
  return suitableArr.join('、');
};

/* 解析客户投资期限 */
const parseUserTerm = (userTerm) => {
  const investTermArr = [
    { term: '1', termText: '短期--1年（含）以内' },
    { term: '2', termText: '中期--5年（含）以内' },
    { term: '3', termText: '长期--期限不限' }
  ];
  if (userTerm.indexOf('3') > -1) {
    userTerm = '3';
  } else if (userTerm.indexOf('2') > -1) {
    userTerm = '2';
  } else if (userTerm.indexOf('1') > -1) {
    userTerm = '1';
  }
  for (let i = 0, len = investTermArr.length; i < len; i += 1) {
    if (investTermArr[i].term == userTerm) {
      return investTermArr[i].termText;
    }
  }
  return '';
};

/* 解析产品投资期限 */
const parseProdTerm = (userTerm) => {
  const investTermArr = [
    { term: '1', termText: '短期--1年（含）以内' },
    { term: '2', termText: '中期--5年（含）以内' },
    { term: '3', termText: '长期--期限不限' }
  ];

  for (let i = 0, len = investTermArr.length; i < len; i += 1) {
    if (investTermArr[i].term == userTerm) {
      return investTermArr[i].termText;
    }
  }
  return '';
};
/* 计算产品的投资期限适用的用户投资期限 */
const parseSuitUserTerm = (investTerm) => {
  const investTermArr = [
    { term: '1', termText: '短期--1年（含）以内' },
    { term: '2', termText: '中期--5年（含）以内' },
    { term: '3', termText: '长期--期限不限' }
  ];
  const suitableArr = [];
  for (let i = 0, len = investTermArr.length; i < len; i += 1) {
    if (investTermArr[i].term >= investTerm) {
      suitableArr.push(investTermArr[i].termText);
    }
  }
  return suitableArr.join('、');
};

// 解析用户投资品种
const parseUserKind = (userKind) => {
  const investKindArr = [
    { value: '1', text: '债券，固定收益凭证，固定收益类资产管理产品或其它固定收益类金融产品等；市场资讯类产品' },
    { value: '2', text: '股票，权益类资产管理产品等权益类金融产品；混合类（投资品种含固收类、权益类、商品及金融衍生品类）金融产品；股票质押式回购，约定购回式证券交易等融资类业务；投资咨询类产品' },
    { value: '3', text: '期货，期权，股权激励融资，融资融券，转融通等信用交易类、杠杆交易类业务；商品及金融衍生品资产管理产品等衍生品类金融产品' },
    { value: '4', text: '结构化金融产品、场外衍生品等复杂或高风险类金融产品或业务、其他金融产品或业务' },
  ];

  if (userKind.indexOf('4') > -1) {
    userKind = '4';
  } else if (userKind.indexOf('3') > -1) {
    userKind = '3';
  } else if (userKind.indexOf('2') > -1) {
    userKind = '2';
  } else if (userKind.indexOf('1') > -1) {
    userKind = '1';
  }
  const tempArr = [];
  for (let i = 0, len = investKindArr.length; i < len; i += 1) {
    if (investKindArr[i].value <= userKind) {
      tempArr.push(investKindArr[i].text);
    }
  }
  return tempArr.join('、');
};

// 解析产品投资品种
const parseProdKind = (investKind) => {
  const investKindArr = [
    { value: '1', text: '债券，固定收益凭证，固定收益类资产管理产品或其它固定收益类金融产品等；市场资讯类产品' },
    { value: '2', text: '股票，权益类资产管理产品等权益类金融产品；混合类（投资品种含固收类、权益类、商品及金融衍生品类）金融产品；股票质押式回购，约定购回式证券交易等融资类业务；投资咨询类产品' },
    { value: '3', text: '期货，期权，股权激励融资，融资融券，转融通等信用交易类、杠杆交易类业务；商品及金融衍生品资产管理产品等衍生品类金融产品' },
    { value: '4', text: '结构化金融产品、场外衍生品等复杂或高风险类金融产品或业务、其他金融产品或业务' },
  ];

  for (let i = 0, len = investKindArr.length; i < len; i += 1) {
    if (investKindArr[i].value == investKind) {
      return investKindArr[i].text;
    }
  }
  return '';
};

// 解析产品适合于哪些客户投资
const parseSuitUserKind = (investKind) => {
  const investKindArr = [
    { value: '1', text: '债券，固定收益凭证，固定收益类资产管理产品或其它固定收益类金融产品等；市场资讯类产品' },
    { value: '2', text: '股票，权益类资产管理产品等权益类金融产品；混合类（投资品种含固收类、权益类、商品及金融衍生品类）金融产品；股票质押式回购，约定购回式证券交易等融资类业务；投资咨询类产品' },
    { value: '3', text: '期货，期权，股权激励融资，融资融券，转融通等信用交易类、杠杆交易类业务；商品及金融衍生品资产管理产品等衍生品类金融产品' },
    { value: '4', text: '结构化金融产品、场外衍生品等复杂或高风险类金融产品或业务、其他金融产品或业务' },
  ];

  const suitableArr = [];
  for (let i = 0, len = investKindArr.length; i < len; i += 1) {
    if (investKindArr[i].value >= investKind) {
      suitableArr.push(investKindArr[i].text);
    }
  }
  return suitableArr.join('、');
};

// 产品代码种类对应键值对
const parseProdcodeKind = (value) => {
  const tempArr = [
    { value: '1', text: '公募基金' },
    { value: '2', text: '券商理财' },
    { value: 'z', text: '其他理财' }
  ];
  for (let i = 0, len = tempArr.length; i < len; i += 1) {
    if (tempArr[i].value === value) {
      return tempArr[i].text;
    }
  }
  return '券商自定义';
};

// 产品代码类型对应键值对
const parseProdcodeType = (value) => {
  const tempArr = [
    { value: '1', text: '股票型基金' },
    { value: '2', text: '货币型基金' },
    { value: '3', text: '偏股型基金' },
    { value: '4', text: '股债平衡型' },
    { value: '5', text: '偏债型' },
    { value: '6', text: '债券型' },
    { value: '7', text: '保本型' },
    { value: '8', text: '指数型' },
    { value: '9', text: '短债型' },
    { value: 'J', text: '资管产品-大集合' },
    { value: 'K', text: '资管产品-小集合' },
    { value: 'L', text: '商品' },
    { value: 'M', text: '股票多空' },
    { value: 'N', text: '资管其他' },
    { value: 'O', text: '公募专户' },
    { value: 'R', text: '收益凭证-固定' },
    { value: 'S', text: '收益凭证-浮动' },
    { value: 'U', text: '资管计划-代销' },
    { value: 'Z', text: '信托' },
    { value: 'a', text: 'QDII基金' },
    { value: 'b', text: '混合基金' },
    { value: 'c', text: '券商理财' },
    { value: 'd', text: '多空杠杆' },
    { value: 'e', text: '私募债' },
    { value: 'f', text: '私募股权' },
    { value: 'g', text: '衍生品' },
    { value: 'h', text: '资产支持证券' },
    { value: 'i', text: '收益凭证' },
    { value: 'j', text: '私募基金' },
    { value: 'm', text: '现金产品' },
    { value: 'n', text: '一对多产品' },
    { value: 'r', text: '养老目标基金' },
    { value: 's', text: '短期理财产品' },
    { value: 'z', text: '其他' }
  ];
  for (let i = 0, len = tempArr.length; i < len; i += 1) {
    if (tempArr[i].value === value) {
      return tempArr[i].text;
    }
  }
  return '券商自定义';
};

/* 解析产品开发状态 */
const parseProdStatus = (prodStatus) => {
  const prodStatusArr = [
    { status: '1', statusText: '开放期' },
    { status: '2', statusText: '认购期' },
    { status: '3', statusText: '预约认购期' },
    { status: '4', statusText: '产品成立' },
    { status: '5', statusText: '产品终止' },
    { status: '6', statusText: '停止交易' },
    { status: '7', statusText: '停止申购' },
    { status: '8', statusText: '停止赎回' },
    { status: 'a', statusText: '非本机构代销' }
  ];
  for (let i = 0, len = prodStatusArr.length; i < len; i += 1) {
    if (prodStatusArr[i].status === prodStatus) {
      return prodStatusArr[i].statusText;
    }
  }
  return '';
};

/* 解析产品开发状态 */
const parseFinanProdStatus = (prodStatus) => {
  const prodStatusArr = [
    { status: '1', statusText: '开放期' },
    { status: '2', statusText: '认购期' },
    { status: '3', statusText: '预约认购期' },
    { status: '4', statusText: '产品成立' },
    { status: '5', statusText: '产品终止' },
    { status: '6', statusText: '停止交易' },
    { status: '7', statusText: '停止申购' },
    { status: '8', statusText: '停止赎回' },
    { status: 'a', statusText: '非本机构代销' }
  ];
  for (let i = 0, len = prodStatusArr.length; i < len; i += 1) {
    if (prodStatusArr[i].status === prodStatus) {
      return prodStatusArr[i].statusText;
    }
  }
  return '';
};

/* 比对后获取用户产品风险等级是否匹配 */
const fourFacCheck = (userInfo, fourFacInfo) => {
  // 默认三要素不匹配：0
  fourFacInfo.riskFlag = '0';
  fourFacInfo.termFlag = '0';
  fourFacInfo.typeFlag = '0';

  // 风险等级匹配
  if (userInfo.userRiskLevel >= fourFacInfo.productRiskLevel) {
    fourFacInfo.riskFlag = '1';
  }
  // 投资期限匹配
  if (userInfo.userInvestTerm >= fourFacInfo.investTerm) {
    fourFacInfo.termFlag = '1';
  }
  // 投资品种匹配
  if (userInfo.userInvestKind >= fourFacInfo.investType) {
    fourFacInfo.typeFlag = '1';
  }
  return fourFacInfo;
};

// 获取涨跌幅字段的class
export function getZdfClassName(value) {
  let className = '';

  if (value === null || typeof value === 'undefined') {
    return '';
  }
  value = parseFloat(value);
  if (value !== 0) {
    className = value > 0 ? 'rise' : value < 0 ? 'drop' : '';
  }
  return className;
}

// 判断元素是否已进入可视区 InsersectionObserver
const isInViewPort = function (el) {
  const viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
  const { top } = el.getBoundingClientRect();
  return top - viewPortHeight <= 100;
};

// 计算倒计时
function _convertLen(data) {
  return data < 10 ? `0${data}` : data;
}

function _formatCountdown(timeDiff) {
  // 剩余天数
  const leftDay = Math.floor(timeDiff / (24 * 60 * 60 * 1000));

  // 剩余小时数
  timeDiff -= (leftDay * 24 * 60 * 60 * 1000);
  const leftHour = Math.floor(timeDiff / (60 * 60 * 1000));

  // 剩余分钟数
  timeDiff -= (leftHour * 60 * 60 * 1000);
  const leftMinute = Math.floor(timeDiff / (60 * 1000));

  // 剩余秒数
  timeDiff -= (leftMinute * 60 * 1000);
  const leftSecond = Math.floor(timeDiff / (1000));

  // 剩余毫秒数
  timeDiff -= (leftSecond * 1000);
  const leftMilliSecond = Math.floor(timeDiff / 10);

  return {
    day: _convertLen(leftDay),
    hour: _convertLen(leftHour),
    minute: _convertLen(leftMinute),
    second: _convertLen(leftSecond),
    millisecond: _convertLen(leftMilliSecond)
  };
}
/**
 *
 * @param {String} startDate 开始时间 2020-08-01
 * @param {String} endDate 结束时间 2020-12-20
 */
export function countdown({ startDate, endDate }) {
  startDate = dayjs(`${startDate}`).format('YYYY/MM/DD');// 以/为分隔符，fix：ios new Date('2020-10-20 23:59:59') Invalid Date
  endDate = dayjs(`${endDate}`).format('YYYY/MM/DD');

  const timeNow = new Date().getTime();
  const timeStart = new Date(startDate).getTime();

  // 结束时间
  const timeEnd = new Date(`${endDate} 23:59:59`).getTime();

  let timeDiff = 0;
  let status = -1;
  if (timeNow < timeStart) {
    // 未开始,离开始时间还有xx天xx时xx分
    timeDiff = timeStart - timeNow;
    status = 0;
  } else if (timeNow > timeEnd) {
    // 已结束
    timeDiff = timeNow - timeEnd;
    status = 1;
  } else {
    timeDiff = timeEnd - timeNow;
    status = 2;
  }

  // 倒计时xx天xx时xx分
  const diffData = _formatCountdown(timeDiff);
  return {
    status,
    diffData
  };
}

// 处理栏目基金数据
export function handleFundColumnData(dataSet) {
  const [columnInfo] = dataSet;
  const prodList = columnInfo.fundColProd || [];
  if (!prodList.length) {
    return { tabList: [], colFundMap: {}, prodList: [] };
  }

  // 基金列表转换为key为tab的map
  const colFundMap = groupBy(prodList, 'tab');
  let tabList = Object.keys(colFundMap).filter(item => colFundMap[item].length);
  // 如果tab有null 或 '',表示没有子栏目
  if (tabList.includes('null') || tabList.includes('')) { //
    tabList = [];
    const nullList = colFundMap.null || [];
    const nullstringList = colFundMap[''] || [];
    colFundMap.parent = nullList.concat(nullstringList); // tab为null和''的基金列表合并，挂parent下
  }
  return { tabList, colFundMap, prodList };
}

export function formatSearchResult(text, keyword) {
  if (keyword.trim() !== '') {
    const reg = new RegExp(`(${keyword})`);
    const result = text.replace(reg, (all, r) => {
      return `<i class="hit">${r}</i>`;
    });
    return result;
  }
}

export default {
  getPurchaseInfo,
  parseProdcodeKind,
  parseProdcodeType,
  parseUserRisk,
  parseProdRisk,
  parseSuitUserRisk,
  parseUserTerm,
  parseProdTerm,
  parseSuitUserTerm,
  parseUserKind,
  parseProdKind,
  parseSuitUserKind,
  parseProdStatus,
  parseFinanProdStatus,
  fourFacCheck,
  getZdfClassName,
  isInViewPort,
  countdown,
  handleFundColumnData,
  formatSearchResult
};